package edu.lab3.service;

import edu.lab3.model.RegionInfection;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Chb
 * date 2020-05-10
 */

@Service
public class VirusDataService {
    private final List<RegionInfection> regionInfectionList = new ArrayList<>();
    public List<RegionInfection> getRegionInfectionList() {
        return regionInfectionList;
    }
//    Seconds Minutes Hours DayofMonth Month DayodWeek
    @Scheduled(cron = "0 0 1 * * *")
    @PostConstruct
    public void fetchVirusData() throws IOException{
        String CORONA_VIRUS_DATA_URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        Reader reader = null;
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        try {
            reader = new InputStreamReader(Objects.requireNonNull(body).getInputStream(), StandardCharsets.UTF_8);
        }catch (IOException e){
            e.printStackTrace();
        }
//        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(reader);
        final CSVParser records = new CSVParser(Objects.requireNonNull(reader), CSVFormat.EXCEL.withHeader());
        try {
            int k=0;
            for (final CSVRecord record : records) {
                String province = record.get("Province/State");
                String country = record.get("Country/Region");
                int totalCases = Integer.parseInt(record.get(record.size()-1));
                int increaseCases = totalCases - Integer.parseInt(record.get(record.size()-2));
                RegionInfection regionInfection = new RegionInfection(
                        k,province,country,totalCases,increaseCases);
                k++;
                regionInfectionList.add(regionInfection);
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            reader.close();
        }


    }

}
